<template>
  在线人数：{{ onlineCount }}
</template>


<script setup>
import { ref } from 'vue'

const onlineCount = ref(0)

const doWs = () => {
  //建立连接(监听websocket)
  let ws = new WebSocket("ws://localhost:8080/websocket")

  if (typeof (WebSocket) == "undefined") {

    console.log("遗憾：您的浏览器不支持WebSocket")
  } else {

    console.log("恭喜：您的浏览器支持WebSocket")
    //连接打开时触发
    ws.onopen = (evt) => {
      console.log("Connection open ...")
    }
  }

  //接收消息时触发
  ws.onmessage = (evt) => {
    console.log("Received Message: ", evt.data)
    onlineCount.value = evt.data

  }
  //连接结束时触发
  ws.onclose = (evt) => {

    console.log("Connection closed...")
  }

  //连接发生错误时触发
  ws.onerror = (evt) => {

    console.log("error")
  }

  //关闭页面前触发
  window.onbeforeunload = (event) => {
    console.log("关闭WebSocket连接！")
    ws.send("关闭页面")
    event.close()
  }

}

onMounted(() => {

  doWs()


})

</script>


<style scoped>
.read-the-docs {
  color: #888;
}
</style>
